const User = require('./User')


//新建用户
const saveUser=async (obj) => {

    let user=new User(obj)
    await user.save();

    return obj
}
exports.saveUser=saveUser



//用户注册
exports.login=async (pic,username,uid,appVersion) => {

    let user=await User.findOne({uid:uid-0})

    //注册过，但是没有appversion
    if(user&&!user.appVersion){
        let user_=await updateUserAppVersion(uid-0,appVersion)
        return user_
    }

    //注册用户
    if(!user){
        let obj={pic:pic,username:username,uid:uid-0,appVersion:appVersion}
        await  saveUser(obj)
        user=await  User.findOne({uid:uid-0})
    }

    return user

}




//判断用户是否存在
exports.isUserExist=async (uid) => {

    let users=await User.findOne({uid}).sort('uid')
    if(users){
        return true
    }
    return false
}







//更新用户头像
exports.updateUser=async (uid,avatar) => {
    let userInfo=await getUserInfo(uid)
    let new_userInfo=Object.assign(userInfo,{pic:avatar})

    let users=await User.update({uid:uid-0},new_userInfo)
    if(!users){
        return []
    }
    return users
}




//获取用户信息
const getUserInfo=async (uid) => {
    let user=await User.findOne({uid:uid-0})

    if(!user){
        return {
            code:1,
            dec:'用户不存在'
        }
    }
    else{
        return user
    }
}
exports.getUserInfo=getUserInfo



exports.removeUser=async (uid) => {
    let res=await User.remove({uid:uid-0})

    return res
}




//获取用户列表

exports.getUserList=async () => {

    let users=await User.find().sort('uid')
    return users
}



exports.getUserListTestByuid=async (uid) => {

    let users=await User.find({uid:uid})
    return users
}



//修改系统消息名称
exports.changeSysName=async (uid,username) => {
    let userInfo=await getUserInfo(uid)
    let new_userInfo=Object.assign(userInfo,{username:username})

    let users=await User.update({uid:uid-0},new_userInfo)
    if(!users){
        return []
    }
    return users
}




exports.isUserInOldAppVersion= async (uid) => {
    let user=await User.findOne({uid:uid-0})
    if(user){
        if(!user.appVersion){   //没有appVersion字段视为旧用户
            return true
        }
    }
    return false
}



//更新用户version
const updateUserAppVersion=async (uid,appVersion) => {
    let userInfo=await getUserInfo(uid)
    let new_userInfo=Object.assign(userInfo,{appVersion:appVersion})

    let user=await User.update({uid:uid-0},new_userInfo)
    if(!user){
        return []
    }
    return user
}

exports.updateUserAppVersion=updateUserAppVersion


